package cn.iocoder.yudao.module.infra.tts.impl.bytedance;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.infra.okhttp.OkHttpUtils;
import cn.iocoder.yudao.module.infra.tts.TTSConfig;
import cn.iocoder.yudao.module.infra.tts.impl.SimpleTTSApi;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service("tts-bytedance")
public class ByteDanceTTSApi extends SimpleTTSApi {
    private TTSConfig.Config byteConfig;

    @Resource
    private TTSConfig ttsConfig;

    @PostConstruct
    public void init() {
        byteConfig = ttsConfig.getService("bytedance");
    }

    @Override
    public String createCloneVoice(String voice_path) {
        throw new UnsupportedOperationException("bytedance 接口的音色, 需要在官方控制台进行创建");
    }

    @Override
    public byte[] convertTextToSpeech(Integer audioToneId, String cloneVoiceId, String voice, String voice_path, String voice_hash, String voice_suffix, String response_format, String input) {
        ByteDanceTtsResponse ttsResponse = voiceClone(cloneVoiceId, input);
        if (ttsResponse.isSuccess()) {
            return ttsResponse.getDecodedData();
        }
        return null;
    }

    public ByteDanceTtsResponse voiceClone(String cloneVoiceId, String text) {
        log.info("文本转语音开始, cloneVoiceId = {}, input = {}", cloneVoiceId, text);
        // 开始时间
        long startTime = System.currentTimeMillis();
        ByteDanceTtsRequest ttsRequest = new ByteDanceTtsRequest(byteConfig.getAppid());
        ttsRequest.setText(text);
        ttsRequest.setSpkId(cloneVoiceId);
        String url = byteConfig.getApiUrl() + "/api/v1/tts";
        RequestBody body = RequestBody.create(JSON.toJSONString(ttsRequest), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Authorization", "Bearer; " + byteConfig.getToken())
                .build();
        try (Response response = OkHttpUtils.getTtsClient().newCall(request).execute()) {
            final String responseBody = response.body() != null ? response.body().string() : null;
            if (response.isSuccessful() && response.body() != null) {
                ByteDanceTtsResponse ttsResponse = JSON.parseObject(responseBody, ByteDanceTtsResponse.class);
                byte[] audioData = ttsResponse.getDecodedData();
                final long duration = System.currentTimeMillis() - startTime;
                log.info("文本转语音完成, cloneVoiceId = {}, audioData.len = {}, input = {}, duration = {}",
                        cloneVoiceId, audioData.length, text, duration);
                return ttsResponse;
            } else {
                if (response.body() != null) {
                    ByteDanceTtsResponse ttsResponse = JSON.parseObject(responseBody, ByteDanceTtsResponse.class);
                    log.error("文本转语音失败, cloneVoiceId = {}, code = {}, body = {}", cloneVoiceId, response.code(), responseBody);
                    return ttsResponse;
                } else {
                    log.error("文本转语音失败, cloneVoiceId = {}, code = {}, body = {}",
                            cloneVoiceId, response.code(), responseBody);
                    throw new RuntimeException(StrUtil.format("文本转语音失败, cloneVoiceId = {}}, code = {}, body = {}",
                            cloneVoiceId, response.code(), responseBody));
                }
            }
        } catch (IOException e) {
            final long duration = System.currentTimeMillis() - startTime;
            log.error(StrUtil.format("文本转语音异常, cloneVoiceId = {}, input = {}, duration = {}", cloneVoiceId, text, duration), e);
            throw new RuntimeException("文本转语音请求异常", e);
        }
    }

}
